from fastapi import APIRouter, Depends, HTTPException, Query
from typing import List, Optional
from models.database import get_db_connection
from models.schemas import (
    OrderCreateWithAddress, OrderUpdateWithAddress, OrderResponse,
    OrderListResponse, SuccessResponse
)
from utils.auth import get_current_user
import mysql.connector
from datetime import datetime

router = APIRouter(prefix="/orders", tags=["订单管理"])


def format_datetime_fields(data):
    """将 datetime 和 bytes 转换为字符串，其他类型保持不变"""
    if isinstance(data, dict):
        for key, value in data.items():
            if isinstance(value, datetime):
                data[key] = value.isoformat()
            elif isinstance(value, (bytes, bytearray)):
                data[key] = value.decode('utf-8')  # 👈 关键！解码 bytes
            elif isinstance(value, (int, float)) and key in ['good_price', 'total_price', 'order_profit']:
                data[key] = float(value)
    return data


@router.get("/", response_model=OrderListResponse)
async def get_user_orders(
        current_user: dict = Depends(get_current_user),
        limit: int = Query(5, description="返回订单数量", ge=1, le=20),
        offset: int = Query(0, description="偏移量", ge=0),
        order_id: Optional[int] = Query(None, description="搜索订单ID"),
        good_id: Optional[int] = Query(None, description="搜索商品ID"),
        keyword: Optional[str] = Query(None, description="搜索关键词（商品名称）")
):
    """获取用户订单列表，支持多种搜索方式"""
    connection = get_db_connection()
    if not connection:
        raise HTTPException(status_code=500, detail="数据库连接失败")

    try:
        cursor = connection.cursor(dictionary=True)

        # 构建查询条件
        where_conditions = ["user_id = %s"]
        params = [current_user['user_id']]

        if order_id:
            where_conditions.append("order_id = %s")
            params.append(order_id)

        if good_id:
            where_conditions.append("good_id = %s")
            params.append(good_id)

        if keyword:
            where_conditions.append("good_name LIKE %s")
            params.append(f"%{keyword}%")

        where_clause = " AND ".join(where_conditions)

        cursor.execute(f"""
            SELECT order_id, user_id, user_name, user_phone, address, good_id, good_name, 
                   good_price, order_number, total_price, order_profit, 
                   order_time, created_at, updated_at
            FROM orders
            WHERE {where_clause}
            ORDER BY order_id DESC
            LIMIT %s OFFSET %s
        """, params + [limit, offset])

        orders = cursor.fetchall()

        formatted_orders = []
        for order in orders:
            print("原始 address 类型:", type(order['address']), "值:", order['address'])  # 👈 打印原始值
            formatted_order = format_datetime_fields(order.copy())
            print("格式化后 address:", formatted_order.get('address'))
            formatted_orders.append(formatted_order)

        cursor.execute(f"SELECT COUNT(*) as total FROM orders WHERE {where_clause}", params)
        total_result = cursor.fetchone()
        total = total_result['total'] if total_result else 0

        message = None
        if order_id and total == 0:
            message = "抱歉未查询到相关订单，请确认订单ID是否正确"
        elif good_id and total == 0:
            message = "未找到该商品的订单记录"
        elif keyword and total == 0:
            message = f"未找到包含'{keyword}'的订单记录"

        return OrderListResponse(
            orders=formatted_orders,
            total=total,
            limit=limit,
            offset=offset,
            user_name=current_user['user_name'],
            message=message
        )

    except mysql.connector.Error as e:
        raise HTTPException(status_code=500, detail=f"数据库错误: {e}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"服务器错误: {e}")
    finally:
        if 'cursor' in locals():
            cursor.close()
        if connection:
            connection.close()


@router.get("/search", response_model=OrderListResponse)
async def search_orders(
        current_user: dict = Depends(get_current_user),
        good_id: Optional[int] = Query(None, description="搜索商品ID"),
        keyword: Optional[str] = Query(None, description="搜索关键词（商品名称）"),
        limit: int = Query(20, description="返回订单数量", ge=1, le=100),
        offset: int = Query(0, description="偏移量", ge=0)
):
    """高级搜索订单（支持商品ID和商品名称搜索）"""
    connection = get_db_connection()
    if not connection:
        raise HTTPException(status_code=500, detail="数据库连接失败")

    try:
        cursor = connection.cursor(dictionary=True)

        where_conditions = ["user_id = %s"]
        params = [current_user['user_id']]

        if good_id:
            where_conditions.append("good_id = %s")
            params.append(good_id)

        if keyword:
            where_conditions.append("good_name LIKE %s")
            params.append(f"%{keyword}%")

        if not good_id and not keyword:
            raise HTTPException(
                status_code=400,
                detail="请提供搜索条件（商品ID或关键词）"
            )

        where_clause = " AND ".join(where_conditions)

        cursor.execute(f"""
            SELECT order_id, user_id, user_name, user_phone, address, good_id, good_name, 
                   good_price, order_number, total_price, order_profit, 
                   order_time, created_at, updated_at
            FROM orders
            WHERE {where_clause}
            ORDER BY order_id DESC
            LIMIT %s OFFSET %s
        """, params + [limit, offset])

        orders = cursor.fetchall()

        formatted_orders = []
        for order in orders:
            print("原始 address 类型:", type(order['address']), "值:", order['address'])  # 👈 打印原始值
            formatted_order = format_datetime_fields(order.copy())
            print("格式化后 address:", formatted_order.get('address'))
            formatted_orders.append(formatted_order)

        cursor.execute(f"SELECT COUNT(*) as total FROM orders WHERE {where_clause}", params)
        total_result = cursor.fetchone()
        total = total_result['total'] if total_result else 0

        search_conditions = []
        if good_id:
            search_conditions.append(f"商品ID: {good_id}")
        if keyword:
            search_conditions.append(f"关键词: '{keyword}'")

        search_description = " + ".join(search_conditions)

        message = None
        if total == 0:
            message = f"未找到{search_description}的订单记录"
        else:
            message = f"找到 {total} 条{search_description}的订单记录"

        return OrderListResponse(
            orders=formatted_orders,
            total=total,
            limit=limit,
            offset=offset,
            user_name=current_user['user_name'],
            message=message
        )

    except mysql.connector.Error as e:
        raise HTTPException(status_code=500, detail=f"数据库错误: {e}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"服务器错误: {e}")
    finally:
        if 'cursor' in locals():
            cursor.close()
        if connection:
            connection.close()


@router.get("/{order_id}", response_model=OrderResponse)
async def get_order_by_id(order_id: int, current_user: dict = Depends(get_current_user)):
    """根据订单ID查询订单详情（包含地址字段）"""
    connection = get_db_connection()
    if not connection:
        raise HTTPException(status_code=500, detail="数据库连接失败")

    try:
        cursor = connection.cursor(dictionary=True)
        cursor.execute("""
            SELECT order_id, user_id, user_name, user_phone, address, good_id, good_name, 
                   good_price, order_number, total_price, order_profit, 
                   order_time, created_at, updated_at
            FROM orders
            WHERE order_id = %s AND user_id = %s
        """, (order_id, current_user['user_id']))

        order = cursor.fetchone()
        if not order:
            raise HTTPException(status_code=404, detail="订单不存在或无权访问")

        formatted_order = format_datetime_fields(order)
        return formatted_order

    except mysql.connector.Error as e:
        raise HTTPException(status_code=500, detail=f"数据库错误: {e}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"服务器错误: {e}")
    finally:
        if 'cursor' in locals():
            cursor.close()
        if connection:
            connection.close()


@router.post("/", response_model=SuccessResponse)
async def create_order(order: OrderCreateWithAddress, current_user: dict = Depends(get_current_user)):
    """创建新订单（包含收货地址）"""
    connection = get_db_connection()
    if not connection:
        raise HTTPException(status_code=500, detail="数据库连接失败")

    try:
        cursor = connection.cursor(dictionary=True)

        cursor.execute("""
            SELECT good_id, good_name, good_number, good_sell_price, good_purchase_price 
            FROM goods WHERE good_id = %s
        """, (order.good_id,))

        product = cursor.fetchone()
        if not product:
            raise HTTPException(status_code=404, detail="商品不存在")

        if product['good_number'] < order.order_number:
            raise HTTPException(
                status_code=400,
                detail=f"库存不足，当前库存：{product['good_number']}"
            )

        good_price = product['good_sell_price']
        total_price = good_price * order.order_number
        profit = (good_price - product['good_purchase_price']) * order.order_number

        cursor.execute("SELECT user_name, user_phone, address FROM user WHERE user_id = %s", (current_user['user_id'],))
        user_info = cursor.fetchone()

        address = order.address if order.address else user_info.get('address')

        if not address:
            raise HTTPException(
                status_code=400,
                detail="请提供收货地址或先设置默认收货地址"
            )

        order_time = datetime.now().strftime("%Y.%m.%d")

        cursor.execute("""
            INSERT INTO orders (user_id, user_name, user_phone, address, good_id, good_name, 
                              good_price, order_number, total_price, order_profit, order_time)
            VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
        """, (
            current_user['user_id'],
            user_info['user_name'],
            user_info['user_phone'],
            address,
            order.good_id,
            product['good_name'],
            good_price,
            order.order_number,
            total_price,
            profit,
            order_time
        ))

        new_order_id = cursor.lastrowid

        cursor.execute("""
            UPDATE goods 
            SET good_number = good_number - %s, good_sell_num = good_sell_num + %s
            WHERE good_id = %s
        """, (order.order_number, order.order_number, order.good_id))

        connection.commit()

        return SuccessResponse(
            success=True,
            message="订单创建成功",
            data={
                "order_id": new_order_id,
                "good_name": product['good_name'],
                "good_price": float(good_price),
                "order_number": order.order_number,
                "total_price": float(total_price),
                "total_profit": float(profit),
                "address": address
            }
        )

    except mysql.connector.Error as e:
        connection.rollback()
        raise HTTPException(status_code=500, detail=f"数据库错误: {e}")
    except Exception as e:
        connection.rollback()
        raise HTTPException(status_code=500, detail=f"服务器错误: {e}")
    finally:
        if 'cursor' in locals():
            cursor.close()
        if connection:
            connection.close()


@router.put("/{order_id}", response_model=SuccessResponse)
async def update_order(
        order_id: int,
        order_update: OrderUpdateWithAddress,
        current_user: dict = Depends(get_current_user)
):
    """更新订单（可更改商品ID、数量和地址）"""
    connection = get_db_connection()
    if not connection:
        raise HTTPException(status_code=500, detail="数据库连接失败")

    try:
        cursor = connection.cursor(dictionary=True)

        cursor.execute("""
            SELECT good_id, order_number, order_profit, good_price, total_price, user_id, address
            FROM orders 
            WHERE order_id = %s AND user_id = %s
        """, (order_id, current_user['user_id']))

        old_order = cursor.fetchone()
        if not old_order:
            raise HTTPException(status_code=404, detail="订单不存在或无权访问")

        cursor.execute("""
            SELECT good_id, good_name, good_number, good_sell_price, good_purchase_price 
            FROM goods WHERE good_id = %s
        """, (order_update.good_id,))

        new_product = cursor.fetchone()
        if not new_product:
            raise HTTPException(status_code=404, detail="新商品不存在")

        stock_change = order_update.order_number - old_order['order_number']
        if new_product['good_number'] < stock_change:
            raise HTTPException(
                status_code=400,
                detail=f"库存不足，当前库存：{new_product['good_number']}，需要：{stock_change}"
            )

        new_good_price = new_product['good_sell_price']
        new_total_price = new_good_price * order_update.order_number
        new_profit = (new_good_price - new_product['good_purchase_price']) * order_update.order_number

        cursor.execute("""
            UPDATE goods 
            SET good_number = good_number + %s, good_sell_num = good_sell_num - %s
            WHERE good_id = %s
        """, (old_order['order_number'], old_order['order_number'], old_order['good_id']))

        cursor.execute("""
            UPDATE goods 
            SET good_number = good_number - %s, good_sell_num = good_sell_num + %s
            WHERE good_id = %s
        """, (order_update.order_number, order_update.order_number, order_update.good_id))

        new_address = order_update.address if order_update.address else old_order['address']

        if not new_address:
            raise HTTPException(
                status_code=400,
                detail="请提供有效的收货地址"
            )

        cursor.execute("""
            UPDATE orders 
            SET good_id = %s, good_name = %s, good_price = %s, 
                order_number = %s, total_price = %s, order_profit = %s,
                address = %s, updated_at = CURRENT_TIMESTAMP
            WHERE order_id = %s AND user_id = %s
        """, (
            order_update.good_id, new_product['good_name'], new_good_price,
            order_update.order_number, new_total_price, new_profit,
            new_address, order_id, current_user['user_id']
        ))

        connection.commit()

        return SuccessResponse(
            success=True,
            message="订单更新成功",
            data={
                "order_id": order_id,
                "new_good_name": new_product['good_name'],
                "new_good_price": float(new_good_price),
                "new_order_number": order_update.order_number,
                "new_total_price": float(new_total_price),
                "new_profit": float(new_profit),
                "address": new_address
            }
        )

    except mysql.connector.Error as e:
        connection.rollback()
        raise HTTPException(status_code=500, detail=f"数据库错误: {e}")
    except Exception as e:
        connection.rollback()
        raise HTTPException(status_code=500, detail=f"服务器错误: {e}")
    finally:
        if 'cursor' in locals():
            cursor.close()
        if connection:
            connection.close()


@router.delete("/{order_id}", response_model=SuccessResponse)
async def delete_order(order_id: int, current_user: dict = Depends(get_current_user)):
    """删除订单"""
    connection = get_db_connection()
    if not connection:
        raise HTTPException(status_code=500, detail="数据库连接失败")

    try:
        cursor = connection.cursor(dictionary=True)

        cursor.execute("""
            SELECT good_id, order_number, user_id
            FROM orders 
            WHERE order_id = %s AND user_id = %s
        """, (order_id, current_user['user_id']))

        order = cursor.fetchone()
        if not order:
            raise HTTPException(status_code=404, detail="订单不存在或无权访问")

        cursor.execute("""
            UPDATE goods 
            SET good_number = good_number + %s, good_sell_num = good_sell_num - %s
            WHERE good_id = %s
        """, (order['order_number'], order['order_number'], order['good_id']))

        cursor.execute("DELETE FROM orders WHERE order_id = %s AND user_id = %s", (order_id, current_user['user_id']))

        connection.commit()

        return SuccessResponse(
            success=True,
            message="订单删除成功",
            data={"order_id": order_id}
        )

    except mysql.connector.Error as e:
        connection.rollback()
        raise HTTPException(status_code=500, detail=f"数据库错误: {e}")
    except Exception as e:
        connection.rollback()
        raise HTTPException(status_code=500, detail=f"服务器错误: {e}")
    finally:
        if 'cursor' in locals():
            cursor.close()
        if connection:
            connection.close()